<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="C语言、嵌入式应用：TCP通信实践, ZhengN_Blog">
    <meta name="description" content="关于socket的笔记，之前已经有分享过两篇相关的文章：
【socket笔记】TCP、UDP通信总结
【socket应用】基于C语言的天气客户端的实现
本篇笔记我们再来一起回顾一下socket相关的知识：我们的开发板作为TCP客户端，与TC">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>C语言、嵌入式应用：TCP通信实践 | ZhengN_Blog</title>
    <link rel="icon" type="image/jpeg" href="/favicon.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">ZhengN_Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">ZhengN_Blog</div>
        <div class="logo-desc">
            
            printf(&#34;每天进步一点点~&#34;);
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/zhengnianli/stm32_weather" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/zhengnianli/stm32_weather" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/4.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        C语言、嵌入式应用：TCP通信实践
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/RT-Thread/" target="_blank">
                                <span class="chip bg-color">RT-Thread</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/嵌入式/" class="post-category" target="_blank">
                                嵌入式
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-06-01
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                        2.6k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                        10 分
                    </div>
                    
                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>关于socket的笔记，之前已经有分享过两篇相关的文章：</p>
<p><a href="https://zhuanlan.zhihu.com/p/104809183" target="_blank" rel="noopener">【socket笔记】TCP、UDP通信总结</a></p>
<p><a href="https://zhuanlan.zhihu.com/p/104969076" target="_blank" rel="noopener">【socket应用】基于C语言的天气客户端的实现</a></p>
<p>本篇笔记我们再来一起回顾一下socket相关的知识：<code>我们的开发板作为TCP客户端，与TCP服务端程序进行通信</code>。</p>
<h2 id="准备相关工程"><a href="#准备相关工程" class="headerlink" title="准备相关工程"></a>准备相关工程</h2><ul>
<li>硬件：小熊派开发板。</li>
<li>软件：STM32+RT-Thread</li>
<li>开发工具：RT-Thread Studio V1.1.0。</li>
</ul>
<p>实验前提是我们的开发板与我们的PC所处的网络环境在同一网段内。</p>
<p>我们的开发板联网模块时ESP8266。这里需要使用RTT的at_device软件包，这在之前的笔记中已经有介绍：<a href="http://mp.weixin.qq.com/s?__biz=MzU5MzcyMjI4MA==&mid=100003867&idx=1&sn=2e739510133c78677d09d90134e37ee6&chksm=7e0d7edc497af7ca997db3722ab7fb93fc6625080785d25e055f01d29466f577f80309c85426#rd" target="_blank" rel="noopener">【RT-Thread笔记】Onenet软件包的使用</a>。</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLITun.jpg" alt><br><img src="https://s1.ax1x.com/2020/06/12/tLI7Bq.jpg" alt></p>
<h2 id="RT-Thread的网络框架"><a href="#RT-Thread的网络框架" class="headerlink" title="RT-Thread的网络框架"></a>RT-Thread的网络框架</h2><p>在编写代码之前有必要先了解一下RT-Thread的网络框架结构（图片来源：RT-Thread官网）：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLIh9g.jpg" alt></p>
<p>从下往上看：</p>
<p>第 1 层：与硬件相关的一些网络模块，这里我们用的是<code>ESP8266</code>。</p>
<p>第 2~4 层：一些中间层。本次实验中我们可以不用深究，我们把这几层看做一个黑盒子，先不用管里面的实现。有精力的朋友可以去研究，<code>初学朋友暂时先别去碰，碰就是劝退。。。</code>不过也可以稍微了解一些这几层是什么。</p>
<p>第 2 层是协议栈层。这些是一些轻量型的、用于嵌入式中的TCP/IP 协议栈 。</p>
<p>第 3 层是网卡层。通过 netdev 网卡层用户可以统一管理各个网卡信息和网络连接状态，并且可以使用统一的网卡调试命令接口。</p>
<p>第 4 层是SAL 套接字抽象层。通过它 RT-Thread 系统能够适配下层不同的网络协议栈，并提供给上层统一的网络编程接口，方便不同协议栈的接入。</p>
<p>第 5 层应用层标准socket接口。其提供一套标准 BSD Socket API。所谓标准就是我们在RT-Thread应用编程中用的网络接口与在PC上进行网络编程所用的接口函数是一样的，如：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLIIjs.jpg" alt></p>
<p>有了这样的一套标准 BSD Socket API，我们的程序就可以在 PC 上编写、调试：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoevd.gif" alt></p>
<p>然后再移植相关代码到 RT-Thread 操作系统上，这给我们提供了很大的便利。</p>
<p>其中，第4层和第5层在在代码中是用宏来关联起来的：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoECD.jpg" alt></p>
<p>更多的关于RT-Thread的网络框架介绍可以查看官网文档：</p>
<blockquote>
<p><a href="https://www.rt-thread.org/document/site/programming-manual/sal/sal/#" target="_blank" rel="noopener">https://www.rt-thread.org/document/site/programming-manual/sal/sal/#</a></p>
</blockquote>
<p>下面开始编写测试代码，首先我们需要清楚一个<code>TCP客户端-服务端模型</code>：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLIjCF.jpg" alt></p>
<h2 id="编写代码"><a href="#编写代码" class="headerlink" title="编写代码"></a>编写代码</h2><h3 id="（1）编写TCP客户端代码（开发板代码）"><a href="#（1）编写TCP客户端代码（开发板代码）" class="headerlink" title="（1）编写TCP客户端代码（开发板代码）"></a>（1）编写TCP客户端代码（开发板代码）</h3><p>我们这里编写的客户端测试代码就是按照上面那个图来一步一步的编写的：</p>
<blockquote>
<p>1、创建一个socket</p>
<p>2、连接服务端</p>
<p>3、发送数据</p>
<p>4、阻塞等待接收数据</p>
<p>5、关闭连接</p>
</blockquote>
<h4 id="①创建一个socket"><a href="#①创建一个socket" class="headerlink" title="①创建一个socket"></a>①创建一个socket</h4><p>用到的接口：</p>
<blockquote>
<p>int socket(int domain, int type, int protocol);</p>
</blockquote>
<p>我们创建socket相关的代码如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/* 创建一个socket，类型是SOCKET_STREAM， TCP类型 */</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>sock_fd <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/* 创建socket失败 */</span>
    <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">"Socket error\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoCHx.jpg" alt></p>
<p><strong>domain / 协议族类型：</strong></p>
<ul>
<li>AF_INET： IPv4</li>
<li>AF_INET6： IPv6</li>
</ul>
<p><strong>type / 协议类型：</strong></p>
<ul>
<li>SOCK_STREAM：流套接字</li>
<li>SOCK_DGRAM： 数据报套接字</li>
<li>SOCK_RAW： 原始套接字</li>
</ul>
<p><strong>protocol / 传输协议</strong></p>
<ul>
<li>IPPROTO_TCP</li>
<li>IPPROTO_UDP</li>
<li>……</li>
</ul>
<h4 id="②连接服务端"><a href="#②连接服务端" class="headerlink" title="②连接服务端"></a>②连接服务端</h4><p>用到的接口：</p>
<blockquote>
<p>int connect(int s, const struct sockaddr *name, socklen_t namelen);</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoiE6.jpg" alt></p>
<p>我们连接服务端相关的代码如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/* 从终端获取URL */</span>
url <span class="token operator">=</span> argv<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 从终端获取端口并转为无符号数据 */</span>
port <span class="token operator">=</span> <span class="token function">strtoul</span><span class="token punctuation">(</span>argv<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 通过函数入口参数url获得host地址（如果是域名，会做域名解析） */</span>
host <span class="token operator">=</span> <span class="token function">gethostbyname</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 初始化预连接的服务端地址 */</span>
server_addr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>
server_addr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span>port<span class="token punctuation">)</span><span class="token punctuation">;</span>
server_addr<span class="token punctuation">.</span>sin_addr <span class="token operator">=</span> <span class="token operator">*</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">struct</span> in_addr <span class="token operator">*</span><span class="token punctuation">)</span>host<span class="token operator">-></span>h_addr<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">rt_memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span><span class="token punctuation">(</span>server_addr<span class="token punctuation">.</span>sin_zero<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>server_addr<span class="token punctuation">.</span>sin_zero<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 连接到服务端 */</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">connect</span><span class="token punctuation">(</span>sock_fd<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr <span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>server_addr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span><span class="token keyword">struct</span> sockaddr<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/* 连接失败 */</span>
    <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">"Connect fail!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">closesocket</span><span class="token punctuation">(</span>sock_fd<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">else</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/* 连接成功 */</span>
    <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">">>>>>>>>>>>>Connect server(%s %d) success!\n"</span><span class="token punctuation">,</span> url<span class="token punctuation">,</span> port<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<h4 id="③发送数据"><a href="#③发送数据" class="headerlink" title="③发送数据"></a>③发送数据</h4><p>用到的接口：</p>
<blockquote>
<p>int send(int s, const void *dataptr, size_t size, int flags);</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoFUK.jpg" alt></p>
<p>我们发送数据相关的代码如下：</p>
<pre class=" language-c"><code class="language-c"> <span class="token comment" spellcheck="true">/* 发送数据 */</span>
 <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">send</span><span class="token punctuation">(</span>sock_fd<span class="token punctuation">,</span> argv<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token function">strlen</span><span class="token punctuation">(</span>argv<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
 <span class="token punctuation">{</span>
     <span class="token comment" spellcheck="true">/* 发送失败，关闭这个连接 */</span>
     <span class="token function">closesocket</span><span class="token punctuation">(</span>sock_fd<span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">"\nsend error,close the socket.\r\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span>
 <span class="token keyword">else</span>
 <span class="token punctuation">{</span>
     <span class="token comment" spellcheck="true">/* 发送成功 */</span>
     <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">">>>>>>>>>>>>Send data(%s) to server success!\n"</span><span class="token punctuation">,</span> argv<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span></code></pre>
<h4 id="④接收数据"><a href="#④接收数据" class="headerlink" title="④接收数据"></a>④接收数据</h4><p>用到的接口：</p>
<blockquote>
<p>int recv(int s, void *mem, size_t len, int flags);</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2020/06/12/tLok4O.jpg" alt></p>
<p>我们接收数据的相关代码如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/* 等待服务端发送过来的数据 */</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">recv</span><span class="token punctuation">(</span>sock_fd<span class="token punctuation">,</span> recv_buf<span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/* 接收失败，关闭这个连接 */</span>
    <span class="token function">closesocket</span><span class="token punctuation">(</span>sock_fd<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">"\nreceived error,close the socket.\r\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">else</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/* 接收成功，打印收到的数据 */</span>
    <span class="token function">rt_kprintf</span><span class="token punctuation">(</span><span class="token string">">>>>>>>>>>>>Recv data from server: %s\n"</span><span class="token punctuation">,</span>recv_buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<h4 id="⑤关闭连接"><a href="#⑤关闭连接" class="headerlink" title="⑤关闭连接"></a>⑤关闭连接</h4><p>用到的接口：</p>
<blockquote>
<p>int closesocket(int s);</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoV8e.jpg" alt></p>
<h3 id="（2）编写TCP服务端代码（PC机）"><a href="#（2）编写TCP服务端代码（PC机）" class="headerlink" title="（2）编写TCP服务端代码（PC机）"></a>（2）编写TCP服务端代码（PC机）</h3><p>这里提供的是Windows环境下的TCP服务端程序代码，编写思路也是按照上面的<code>TCP客户端-服务端模型</code>来的，相关接口就不详细列举了，直接贴代码吧：</p>
<pre class=" language-c"><code class="language-c"><span class="token comment" spellcheck="true">/*    程序：Windows环境下的TCP服务端程序
    gcc编译命令：gcc tcp_server.c -lwsock32 -o tcp_server.exe

    微信公众号：嵌入式大杂烩
    作者：ZhengN
*/</span>

<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;winsock2.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> BUF_LEN  100</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    WSADATA wd<span class="token punctuation">;</span>
    SOCKET ServerSock<span class="token punctuation">,</span> ClientSock<span class="token punctuation">;</span>
    <span class="token keyword">char</span> Buf<span class="token punctuation">[</span>BUF_LEN<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    SOCKADDR ClientAddr<span class="token punctuation">;</span>
    SOCKADDR_IN ServerSockAddr<span class="token punctuation">;</span>
    <span class="token keyword">int</span> addr_size <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> recv_len <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* sock需要 */</span>
    <span class="token function">WSAStartup</span><span class="token punctuation">(</span><span class="token function">MAKEWORD</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token operator">&amp;</span>wd<span class="token punctuation">)</span><span class="token punctuation">;</span>  

    <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"===============这是一个TCP服务端程序==============\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 创建服务端socket */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ServerSock <span class="token operator">=</span> <span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span> SOCK_STREAM<span class="token punctuation">,</span> IPPROTO_TCP<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 设置服务端信息 */</span>
    <span class="token function">memset</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>ServerSockAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>         <span class="token comment" spellcheck="true">// 给结构体ServerSockAddr清零</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_family <span class="token operator">=</span> AF_INET<span class="token punctuation">;</span>                          <span class="token comment" spellcheck="true">// 使用IPv4地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_addr<span class="token punctuation">.</span>s_addr <span class="token operator">=</span> <span class="token function">inet_addr</span><span class="token punctuation">(</span><span class="token string">"192.168.1.101"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true">// 本机IP地址</span>
    ServerSockAddr<span class="token punctuation">.</span>sin_port <span class="token operator">=</span> <span class="token function">htons</span><span class="token punctuation">(</span><span class="token number">1314</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                      <span class="token comment" spellcheck="true">// 端口</span>

    <span class="token comment" spellcheck="true">/* 绑定套接字 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">bind</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ServerSockAddr<span class="token punctuation">,</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"bind error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 进入监听状态 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token function">listen</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"listen error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    addr_size <span class="token operator">=</span> <span class="token keyword">sizeof</span><span class="token punctuation">(</span>SOCKADDR<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">/* 监听客户端请求，accept函数返回一个新的套接字，发送和接收都是用这个套接字 */</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span> <span class="token operator">==</span> <span class="token punctuation">(</span>ClientSock <span class="token operator">=</span> <span class="token function">accept</span><span class="token punctuation">(</span>ServerSock<span class="token punctuation">,</span> <span class="token punctuation">(</span>SOCKADDR<span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>ClientAddr<span class="token punctuation">,</span> <span class="token operator">&amp;</span>addr_size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"socket error!\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">/* 接受客户端的返回数据 */</span>
        <span class="token keyword">int</span> recv_len <span class="token operator">=</span> <span class="token function">recv</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"客户端发送过来的数据为：%s\n"</span><span class="token punctuation">,</span> Buf<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 发送数据到客户端 */</span>
        <span class="token function">send</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">,</span> Buf<span class="token punctuation">,</span> recv_len<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 关闭客户端套接字 */</span>
        <span class="token function">closesocket</span><span class="token punctuation">(</span>ClientSock<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 清空缓冲区 */</span>
        <span class="token function">memset</span><span class="token punctuation">(</span>Buf<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> BUF_LEN<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/*如果有退出循环的条件，这里还需要清除对socket库的使用*/</span>
    <span class="token comment" spellcheck="true">/* 关闭服务端套接字 */</span>
    <span class="token comment" spellcheck="true">//closesocket(ServerSock);</span>
    <span class="token comment" spellcheck="true">/* WSACleanup();*/</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<h2 id="验证、分析"><a href="#验证、分析" class="headerlink" title="验证、分析"></a>验证、分析</h2><h3 id="1、PC端自验证"><a href="#1、PC端自验证" class="headerlink" title="1、PC端自验证"></a>1、PC端自验证</h3><p>我们使用我们自己用C语言编写的客户端、服务端程序进行验证：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoevd.gif" alt></p>
<h3 id="2、STM32-lt-–-gt-PC"><a href="#2、STM32-lt-–-gt-PC" class="headerlink" title="2、STM32&lt;–&gt;PC"></a>2、STM32&lt;–&gt;PC</h3><p><strong>（1）STM32作为客户端，与PC端我们自己编写的服务端程序进行通信。</strong></p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoZgH.jpg" alt></p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoG8g.gif" alt></p>
<p>tcp_client命令是我们使用<code>MSH_CMD_EXPORT</code>宏导出的命令，如</p>
<blockquote>
<p>MSH_CMD_EXPORT(tcp_client, tcp_client sample);</p>
</blockquote>
<p>我们可在终端按下<code>TAB键</code>或者输入<code>help</code>来查看有没有导出成功：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLonKA.jpg" alt></p>
<p>我们的测试命令格式为：</p>
<blockquote>
<p>tcp_client URL PORT DATA</p>
</blockquote>
<p>其中，URL 参数代表网址或IP地址，这里是局域网内的TCP通信测试，所以这个参数其实就是我们电脑的IP地址，可以在cmd下输入<code>ipconfig</code>命令进行查看：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLouDI.jpg" alt></p>
<p>PORT 参数代表端口。这里要输入的是服务端程序绑定的端口号。端口使用16bit进行编号，即其范围为： <code>0~65536</code>。</p>
<p>但 <code>0~1023</code> 的端口一般由系统分配给特定的服务程序，例如 Web 服务的端口号为 80，FTP 服务的端口号为 21等。</p>
<p>我们这里的服务端程序端口号可以设置为<code>1024~65535</code>范围内的随意一个数。但要注意的是我们输入的测试命令中的PORT参数要与服务端程序绑定的端口一样，否则客户端就连接不上服务端：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLolUf.jpg" alt></p>
<p>DATA参数代表我们要发送给服务端的数据。</p>
<p>需要注意的是，我们在进行测试时需要<code>先启动服务端程序</code>。如果服务端程序还未启动就运行我们的客户端程序，就会出现连接失败：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLo158.jpg" alt></p>
<p><strong>（2）STM32作为客户端，PC端网络调试助手作为服务端。</strong></p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoKbt.jpg" alt></p>
<p>从这个网络助手中可以看到在收到数据的同时可以显示出客户端的IP及端口号。<code>客户端的端口号是系统随机分配的</code>（范围为：1024~65535）：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoQVP.jpg" alt></p>
<p>所以我们不关心端口号，但是我们可以查看客户端的IP地址。如：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLo8PS.jpg" alt></p>
<p>除了这个串口调试助手之外，之前也有分享过一个很好用的socket编程调试工具，有兴趣的朋友可移步至：<a href="https://zhuanlan.zhihu.com/p/120027361" target="_blank" rel="noopener">《网络调试助手的使用》</a>进行查看。</p>
<p><strong>（3）Python实现服务端</strong></p>
<p>服务端程序可以用C、C++、Python等语言来编写，上面我们用的是C语言。这里我们也来过一把Python隐：</p>
<p><img src="https://s1.ax1x.com/2020/06/12/tLoYvj.jpg" alt></p>
<p><strong>Python代码：</strong></p>
<p>以下Python代码来自CSDN博客。博客链接：</p>
<pre class=" language-c"><code class="language-c">https<span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span>blog<span class="token punctuation">.</span>csdn<span class="token punctuation">.</span>net<span class="token operator">/</span>liao392781<span class="token operator">/</span>article<span class="token operator">/</span>details<span class="token operator">/</span><span class="token number">80116600</span><span class="token operator">?</span>utm_medium<span class="token operator">=</span>distribute<span class="token punctuation">.</span>pc_relevant<span class="token punctuation">.</span>none<span class="token operator">-</span>task<span class="token operator">-</span>blog<span class="token operator">-</span>BlogCommendFromMachineLearnPai2<span class="token number">-1</span><span class="token punctuation">.</span>nonecase<span class="token operator">&amp;</span>depth_1<span class="token operator">-</span>utm_source<span class="token operator">=</span>distribute<span class="token punctuation">.</span>pc_relevant<span class="token punctuation">.</span>none<span class="token operator">-</span>task<span class="token operator">-</span>blog<span class="token operator">-</span>BlogCommendFromMachineLearnPai2<span class="token number">-1</span><span class="token punctuation">.</span>nonecase</code></pre>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#coding=utf-8</span>
#创建TCP服务器
from socket import <span class="token operator">*</span>
from time import ctime

HOST<span class="token operator">=</span><span class="token string">'192.168.1.101'</span> #这个是我的服务器ip，根据情况改动
PORT<span class="token operator">=</span><span class="token number">1314</span> #我的端口号
BUFSIZ<span class="token operator">=</span><span class="token number">1024</span>
ADDR<span class="token operator">=</span><span class="token punctuation">(</span>HOST<span class="token punctuation">,</span>PORT<span class="token punctuation">)</span>

tcpSerSock<span class="token operator">=</span><span class="token function">socket</span><span class="token punctuation">(</span>AF_INET<span class="token punctuation">,</span>SOCK_STREAM<span class="token punctuation">)</span> #创服务器套接字
tcpSerSock<span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>ADDR<span class="token punctuation">)</span> #套接字与地址绑定
tcpSerSock<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>  #监听连接<span class="token punctuation">,</span>传入连接请求的最大数，一般为<span class="token number">5</span>就可以了

<span class="token keyword">while</span> True<span class="token punctuation">:</span>
    <span class="token function">print</span><span class="token punctuation">(</span><span class="token string">'waiting for connection...'</span><span class="token punctuation">)</span>
    tcpCliSock<span class="token punctuation">,</span>addr <span class="token operator">=</span>tcpSerSock<span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token function">print</span><span class="token punctuation">(</span><span class="token string">'...connected from:'</span><span class="token punctuation">,</span>addr<span class="token punctuation">)</span>

    <span class="token keyword">while</span> True<span class="token punctuation">:</span>
        stock_codes <span class="token operator">=</span> tcpCliSock<span class="token punctuation">.</span><span class="token function">recv</span><span class="token punctuation">(</span>BUFSIZ<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span><span class="token punctuation">)</span> #收到的客户端的数据需要解码（python3特性）
        <span class="token function">print</span><span class="token punctuation">(</span><span class="token string">'stock_codes = '</span><span class="token punctuation">,</span>stock_codes<span class="token punctuation">)</span>    #传入参数stock_codes
        <span class="token keyword">if</span> not stock_codes<span class="token punctuation">:</span>
            <span class="token keyword">break</span>
        tcpCliSock<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token string">'[%s] %s'</span> <span class="token operator">%</span><span class="token punctuation">(</span><span class="token function">ctime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>stock_codes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">encode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  #发送给客户端的数据需要编码（python3特性）
        after_close_simulation <span class="token operator">=</span> tcpCliSock<span class="token punctuation">.</span><span class="token function">recv</span><span class="token punctuation">(</span>BUFSIZ<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span><span class="token punctuation">)</span> #收到的客户端的数据需要解码（python3特性）
        <span class="token function">print</span><span class="token punctuation">(</span><span class="token string">'after_close_simulation = '</span><span class="token punctuation">,</span>after_close_simulation<span class="token punctuation">)</span>    #传入参数after_close_simulation
        <span class="token keyword">if</span> not after_close_simulation<span class="token punctuation">:</span>
            <span class="token keyword">break</span>
        tcpCliSock<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token string">'[%s] %s'</span> <span class="token operator">%</span><span class="token punctuation">(</span><span class="token function">ctime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>after_close_simulation<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">encode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  #发送给客户端的数据需要编码（python3特性） 

    tcpCliSock<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
tcpSerSock<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>以上就是本次的分享。如果觉得文章不错，转发分享、在看，也是我们继续更新的动力。</p>
<hr>
<p>我的个人博客：<a href="https://www.lizhengnian.cn/">https://www.lizhengnian.cn/</a></p>
<p>我的微信公众号：嵌入式大杂烩</p>
<p>我的CSDN博客：<a href="https://blog.csdn.net/zhengnianli" target="_blank" rel="noopener">https://blog.csdn.net/zhengnianli</a></p>
<p><img src="https://s1.ax1x.com/2020/06/22/NGV7Oe.png" alt></p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">欢迎关注ZhengN的微信公众号</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <!--<ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微信公众号</a></li>
                    </ul>-->
					<!--
                    <div id="alipay">
                        <img src="" class="reward-img" alt="支付宝打赏二维码">
                    </div>
					-->
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信公众号二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            


        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments input[type=text],
    #vcomments input[type=email],
    #vcomments input[type=url],
    #vcomments textarea {
        box-sizing: border-box;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #42b983;
        font-weight: 500;
        text-decoration: underline;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div id="vcomments" class="card-content"></div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'Vc276uuqkd8y8heuqzShe9p1-gzGzoHsz',
        appKey: 'bUwy6lANpgeVdpcQamMtC8QD',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '快来快活呀！^_^'
    });
</script>
    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/06/03/rt-thread-bh1750-ruan-jian-bao-de-shi-yong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="【RT-Thread】BH1750软件包的使用">
                        
                        <span class="card-title">【RT-Thread】BH1750软件包的使用</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            BH1750简介BH1750是一种用于两线制串行总线接口的16位数字型光强度传感器集成电路。利用它的高分辨率可以探测较大范围的光强度变化。（1lx~65535lx）。

创建工程、验证在RT-Thread中读取BH1750数据有两种方法：一
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2020-06-03
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RT-Thread/" class="post-category" target="_blank">
                                    RT-Thread
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/BH1750/" target="_blank">
                        <span class="chip bg-color">BH1750</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/06/01/rt-thread-onenet-ruan-jian-bao-de-shi-yong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/14.jpg" class="responsive-img" alt="【RT-Thread】OneNet软件包的使用">
                        
                        <span class="card-title">【RT-Thread】OneNet软件包的使用</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            去年，RT-Thread发布了RT-Thread Studio初版RT-ThreadStudio的使用体验，经过不断更新迭代之后，来到了V1.1.0，咱也来拥抱一下新版本。
本篇笔记咱们以接入OneNet云平台实验来实操一下：使用RT-Th
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2020-06-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RT-Thread/" class="post-category" target="_blank">
                                    RT-Thread
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/OneNet软件包/" target="_blank">
                        <span class="chip bg-color">OneNet软件包</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站由&copy;<a href="https://zhengnianli.github.io/" target="_blank">ZhengNian</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题搭建.

            
                &nbsp;<i class="fa fa-area-chart"></i>&nbsp;站点总字数:&nbsp;
                <span class="white-color">187.2k</span>
            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhengnianli" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:2238184039@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2238184039" class="tooltipped" data-tooltip="QQ联系我: 2238184039" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->



    <script src="/libs/others/clicklove.js"></script>


    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>